/**
 * @author Endre Marczi
 * 
 * This class handles the model part of the listing of matching contacts.
 */

package ch.ffhs.radarpp;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import ch.ffhs.radarpp.managers.PersistentDataManager;
import ch.ffhs.radarpp.managers.ProfilePictureDataManager;
import ch.ffhs.radarpp.managers.WebRequestManager;
import ch.ffhs.radarpp.model.InviteFriendListItem;
import ch.ffhs.radarpp.model.LoginInformation;
import ch.ffhs.radarpp.web.WebClient;
import ch.ffhs.radarpp.web.WebManager;

public class InviteFriendAdapter extends ArrayAdapter<InviteFriendListItem> implements WebClient {
	private static final Object FINDFRIEND = "findfriend";
	private static final Object ADDFRIEND = "addfriend";

	private Context context;
	private int layoutResourceId;

	private WebManager webManager;

	private ArrayList<InviteFriendListItem> internalItems = new ArrayList<InviteFriendListItem>();

	public InviteFriendAdapter(Context context, int resource) {
		super(context, resource);

		this.layoutResourceId = resource;
		this.context = context;

		webManager = new WebManager(this, PersistentDataManager.getAppSettings(context));
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;

		InviteFriendListItem item = getItem(position);

		if (row == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			row = inflater.inflate(layoutResourceId, parent, false);

			row.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					InviteFriendListItem item = (InviteFriendListItem) v.getTag();
					((InviteFriendActivity) context).showWaitingMessage(getContext().getString(R.string.please_wait));

					webManager.executeHTTPRequest(WebRequestManager.createBecomeFriendsRequest(context, item.getUserId()), ADDFRIEND);
				}
			});
		}

		row.setTag(item);

		System.out.println("Position=" + position);

		((TextView) row.findViewById(R.id.inviteUI_listing_username)).setText(item.getDisplayName());
		((ImageView) row.findViewById(R.id.inviteUI_listing_picture)).setImageBitmap(ProfilePictureDataManager.getBitmapFromJson(item.getPicture(), context.getResources()));

		if (item.isInternalPhoneContact()) {
			((TextView) row.findViewById(R.id.inviteUI_listing_displayName)).setText(item.getPhoneName());
			((TextView) row.findViewById(R.id.inviteUI_listing_typelabel)).setText(R.string.from_phonebook);
		} else {
			((TextView) row.findViewById(R.id.inviteUI_listing_typelabel)).setText(R.string.from_radarpp);
		}

		row.setTag(item);

		return row;
	}

	public void applyFilter(String filter) {
		LoginInformation login = PersistentDataManager.getLoginInfo(context);

		((InviteFriendActivity) context).showWaitingMessage(getContext().getString(R.string.looking_for_friends));

		webManager.executeHTTPRequest(String.format(getContext().getString(R.string.service_findfriend), login.getUsername(), login.getPassword(), filter), FINDFRIEND);
	}

	public void updateInternalContacts(ArrayList<InviteFriendListItem> internalContacts) {
		this.internalItems = internalContacts;
		addAll(internalContacts);
		notifyDataSetChanged();
	}

	@Override
	public void requestCompleted(String result, Object context) {

		Log.d("findfriend", result);

		((InviteFriendActivity) this.context).closeMessage();

		try {
			if (context.equals(ADDFRIEND)) {

				JSONObject o = new JSONObject(result);

				if (o.getBoolean(getContext().getString(R.string.invitationresult_successfull))) {
					((InviteFriendActivity) this.context).showMessage(getContext().getString(R.string.invitation_success));
				} else {
					((InviteFriendActivity) this.context).showMessage(getContext().getString(R.string.invitation_no_success));
				}
			} else if (context.equals(FINDFRIEND)) {
				clear();

				JSONObject o = new JSONObject(result);

				if (o.getBoolean(getContext().getString(R.string.invitationresult_successfull))) {
					JSONArray arr = o.getJSONArray("data");

					for (int i = 0; i < arr.length(); i++) {

						JSONObject friend = arr.optJSONObject(i);
						InviteFriendListItem item = new InviteFriendListItem(friend.getString(getContext().getString(R.string.findfriend_username)), 
								friend.getInt(getContext().getString(R.string.findfriendresult_userid)), 
								friend.getString(getContext().getString(R.string.findfriendresult_picture)));

						add(item);
					}
				}

				addAll(this.internalItems);

				notifyDataSetChanged();

			}
		} catch (JSONException e) {
			e.printStackTrace();

		}

	}

	@Override
	public void requestFailed(Exception e, Object context) {
		((InviteFriendActivity) this.context).showMessage(this.context.getString(R.string.common_request_failed));
	}

}
